package com.xinnet.mms.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.providers.encoding.MessageDigestPasswordEncoder;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.core.utils.INetUtils;
import com.xinnet.mms.authip.dao.AuthIpDao;
import com.xinnet.mms.authip.service.AuthIpService;
import com.xinnet.mms.entity.AuthIp;
import com.xinnet.mms.quartz.job.CustomAllotJob;


/**
 * 
 * IP信任过滤器
 * @author 王志军
 * @since 2016-5-18
 *
 */
public class IpFilter implements Filter {
	
	private static Log log = LogFactory.getLog(IpFilter.class);
	
	AuthIpService authIpService = null;
	@Override
	public void destroy() {

	}


	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		response.setContentType("text/html;charset=utf-8");
		
		String clientIP = INetUtils.getClientIpAddr(request);  //获取客户端IP地址
		AuthIp ip = new AuthIp();
		ip.setIp(clientIP);
		AuthIp authIp = authIpService.getAuthIpByIp(ip);
		if(authIp!=null){
			String state = authIp.getState();
			if(state!=null && "1".equals(state)){
				chain.doFilter(req, res); //放行
				//log.info("===============>IP验证通过");
			} else {
				//response.getWriter().print("拒绝访问！");
				chain.doFilter(req, res); //放行
				log.info("===============>IP验证不通过,不在信任列表中,ip:"+clientIP);
			}
		} else {
			//response.getWriter().print("拒绝访问！");
			chain.doFilter(req, res); //放行
			log.info("===============>IP验证不通过,不在信任列表中,ip:"+clientIP);
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ServletContext sc = filterConfig.getServletContext();
		ApplicationContext ac = (ApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		authIpService = (AuthIpService) ac.getBean("authIpService");
	}

	
	
}
